import React, { Component } from 'react'
//路由传参
import {withRouter} from "react-router-dom"
import {Modal, Button, WhiteSpace, WingBlank,Toast,Carousel} from "antd-mobile"
import "./index.scss"
import IntegralTs from '../../assets/img/integral-ts.png'
import IntegralLw from '../../assets/img/integral-lw.png'
import IntegralMx from '../../assets/img/integral-mx.png'
import IntegralZs from '../../assets/img/integral-zs.png'
import Axios from 'axios'
import { BASE_URL } from '../../utils/requestPath'
import requestAxios from '../../utils/myaxios'
import GoodsIntegral from '../goodsIntegral/index'
import Jump from '../../assets/img/navigator_jump.png'
const userInfoIns = localStorage.getItem("userInfoIns")
const user = JSON.parse(userInfoIns) || {}
const operation = Modal.operation;
var timeJump;
var goodsTime;
class Index extends Component {

    state = {
        reSet:"<",
        userCountIntegral:0,
        getUserInfo:{},
        userInfoNew:{}, 
        localStorageExChangeJumpStart:0,
        integralStartZindex:0,
        ltStartJump:0,
        integralDetail:false,
        data: ['1', '2', '3'],
        imgHeight: 176,
        integralDetailIns:{},
        mainIntegralExchange:0,
        jumpIntegral:500,
        marginTop:null

    }

    handleClick = (params) => {
        this.props.history.push("/searchCenter");
    }
    
    escOnClick=()=>{
        this.props.history.goBack()
    }

    async componentDidMount(){
        await window.addEventListener('scroll', this.handleScroll);
        if(this.state.userInfoNew.jumpStart === 1){
            this.setState({
                mainIntegralExchange:1000
            })
        }

        document.title="积分中心"
        console.log("进来了.........")
        await this.componentIntegral()
        await this.getUserInfo()

        const userInfoIns =await localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}

        if(user !== undefined){
           await setInterval(() => {
                this.componentIntegral()
            }, 3000);
        }

        if(user.platformAddress === 2){
            this.setState({
                ltStartJump:1000
            })
        }

        timeJump = setInterval(()=>{
            this.getJumpStart()
        },1000)

        const jumpStart = localStorage.getItem("jumpStart")
        const jumpStartStr = JSON.parse(jumpStart) || {}
        if(jumpStartStr !== 3){
            this.setState({
                localStorageExChangeJumpStart:0
            })
        }

        goodsTime = setInterval(()=>{
            if(jumpStartStr === 1){
                this.onChangeState()
            }
        },1000)

    }

    requestAxiosJump = () =>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
          const id = user.id;
          const jumpStart = 1;
          const jumpStartTwo = 1;
          const userInfo = {id,jumpStart,jumpStartTwo};
          requestAxios.put(BASE_URL+"/api/user/update",userInfo).then(res=>{
                console.log(res)
          })
      }
    
    getUserInfo= async()=>{

        const userInfoIns =await localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
    
        await requestAxios.get(BASE_URL+"/api/user/getid/"+user.id).then(res=>{
           this.setState({
            userInfoNew:res.data
           })
        })
      }

    componentIntegral=()=>{
        const userInfos = localStorage.getItem("userInfoIns");
        const userInfoIns = JSON.parse(userInfos) || {};
        console.log("integral.......打印")
        console.log(userInfoIns)

        if(userInfoIns){
            //获取用户当前的积分
            requestAxios.get(BASE_URL+"/api/integral/find/list/"+userInfoIns.id).then(res=>{
                console.log(res.data)
                this.setState({
                    userCountIntegral:res.data
                })
            })
        }

        // const mainIntegralExchange = localStorage.setItem("");
        // const mainINtegralEx = JSON.parse(mainIntegralExchange);

    }

    oneOnHanldClick = ()=>{
        console.log("300日元")
    }

    twoOnHanldClick=()=>{

        console.log("500日元")
    }

    threeOnHanldClick=()=>{

        console.log("1000日元")
    }

    earnIntegral=()=>{

        console.log("赚积分")
        this.props.history.push("/orderInformation")
    }

    recordIntegralClick=()=>{

        //点击兑换记录后,清空状态...
        this.setState({
            localStorageExChangeJumpStart:0,
            mainIntegralExchange:900
        })

        localStorage.removeItem("jumpStart")
        //乐天,雅虎用户....点击记录后清楚定时器.....
        clearInterval(goodsTime)
        console.log("兑换记录")
        this.props.history.push("/exchangerecord")
    }

    detailedIntegralClick=()=>{

        console.log("积分明细")
        this.props.history.push("/integraldetailed")
    }

   integralExchangeRequest(count){
        //兑换用户id
        const integralUserId = localStorage.getItem("userInfoIns");
        const integralUserInfo = JSON.parse(integralUserId) || {}

        //用多少积分兑换 
        if(integralUserInfo.id){
            let zgUserId = integralUserInfo.id;
            let couponCount = parseInt(count);
            let integral = {zgUserId,couponCount};
            requestAxios.post(BASE_URL+"/api/coupon/add",integral).then(res=>{
                if(res.data.flag){
                    console.log("兑换成功,请在兑换记录列表查看")
                    Toast.success('兑换成功,存入兑换列表!!!', 2);
                    this.componentIntegral()
                }else{
                    Toast.offline(res.data.message, 1);
                    return;
                }
            })
        }
        
    }

    //子组件更新父组件状态
    async onChangeState(){
        // //添加缓存赋值....2
        await localStorage.setItem("jumpStartTwoIns",2)

        await this.componentIntegral()
        //await this.props.onClickedGood()
        //goods 点击触发的事件
        const jumpStart = localStorage.getItem("jumpStart");
        const jumpStartStr = JSON.parse(jumpStart)
        //修改数据库第一层.....
        //await this.requestAxiosJump()

        if(jumpStartStr === 1){
            this.setState({
                localStorageExChangeJumpStart:1,
                integralStartZindex:900
            })
        }
    }

    //跳过指引,,亚马逊用户第二步骤...... 乐天雅虎用户第二步骤
    clearNaviagtorOrderTop=()=>{

        //request 请求.....
        localStorage.setItem("jumpStartTwo",2)
        //this.props.fuOnClickedStart()
        //alert("清除..........")

        //修改数据库状态....
        this.requestAxiosJumpTwo()
    }

    //第二层状态......
    requestAxiosJumpTwo = () =>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
          const id = user.id;
          const jumpStartTwo = 1;
          const userInfo = {id,jumpStartTwo};
          requestAxios.put(BASE_URL+"/api/user/update",userInfo).then(res=>{
                console.log(res)
          })
      }

    getJumpStart=()=>{
        const jumpStartStrTwo = localStorage.getItem("jumpStartTwo")
        const jumpStartStrTwos = JSON.parse(jumpStartStrTwo)
        if(jumpStartStrTwos === 2){
            clearInterval(timeJump)
            return;
        }
        const jumpStart = localStorage.getItem("jumpStart")
        const jumpStartStr = JSON.parse(jumpStart) || {}
        console.log(jumpStartStr)

        //如果缓存对象为null,第二步骤,亚马逊背景为true
        if(jumpStartStr === 3){
            this.setState({
                localStorageExChangeJumpStart:1,
                integralStartZindex:900
            })
        } 
    }

    //优惠券详情
    onIntegralClickDetail=(type)=>{

        this.onChangeState()

        let integralTitle = "";
        let integralCountSum = 0;
        
        if(type === "1"){
            // 300日元优惠券
            integralTitle = "300日元优惠券";
            integralCountSum = 3000;
        }else if(type === "2"){
            // 500 日元优惠券
            integralTitle = "500日元优惠券";
            integralCountSum = 5000;
        }else if(type === "3"){
            // 1000日元优惠券
            integralTitle = "1000日元优惠券";
            integralCountSum = 10000;
        }
        const integralDetail = {integralTitle,integralCountSum};

        this.setState({
            integralDetail:true,
            integralDetailIns:integralDetail
        })
    }

    //关闭优惠券
    clearGoodsDetail=()=>{
        this.setState({
            integralDetail:false
        })
    }

    
    render() {
        const {reSet,userCountIntegral,integralDetailIns} = this.state
        return (
          <div className="main-integral">
             {/* 头部,返回,评价 */}
             <header className="main-integral-header">
                <div className="main-integral-header-con" onClick={this.escOnClick}>
                    <span className="main-integral-header-con-span-one">{reSet}</span>
                    <span  className="main-integral-header-con-span-two">戻る</span>
                </div>
                <h4>
                    代金引換
                </h4>
                <img src={IntegralTs}></img>
            </header>

            {/* 积分余额 */}
            <div className="main-integral-balance">
                <h3>利用可能ポイント</h3>
                <h4>{userCountIntegral}</h4>
            </div>

            {/* 赚取积分, 兑换记录, 积分明细 */}
            <div className="main-integral-log">
                <div className="main-integral-left" onClick={this.earnIntegral}>
                    <img src={IntegralZs}></img>
                    <h3>ポイントをもらう</h3>
                </div>

                <div className="main-integral-content"
                style={{zIndex:0,background:"#fff"}}
                onClick={this.recordIntegralClick}>
                    <img src={IntegralLw}></img>
                    <h3>引換履歴</h3>
                </div>

                <div className="main-integral-right" onClick={this.detailedIntegralClick}>
                    <img src={IntegralMx}></img>
                    <h3>ポイント明細</h3>
                </div>
            </div>

            {/* 积分兑换 */}
            {this.state.userInfoNew.platformAddress === 2?
                <div className="main-integral-exchange"
                style={{}}
                >
                <h4>代金引換</h4>
                <div className="main0integral-300-500-1000">
                    {/* 300日元优惠券 */}
                    <div className="main-integral-300" 
                    style={{
                        background:"#fff",
                        position:"relative",
                        zIndex:this.state.jumpIntegral
                    }}
                    >
                        <div className="main-integral-top"
                        onClick={this.onIntegralClickDetail.bind(this,"1")}>
                            <h4>300</h4> <h5>クーポン</h5>
                        </div>

                        <Button 
                        className="main-integral-bottom"
                        style={{fontSize:14,}}
                        onClick={() => operation([
                            { text:'3000ポイント＝300円',style:{textAlign:'center',color:"rgb(235, 37, 4)",fontWeight:900}},
                            { text: 'すでに代金引換',style:{background:"skyblue",color:"#fff",textAlign:"center"}, onPress: () => {
                                if(userCountIntegral < 3000){
                                    Toast.offline('残高が足りない、レビューを書いてポイントが貯まる !!!', 1);
                                    return;
                                }
                                console.log("发请求.....300")
                                Toast.loading('Loading...', 1, () => {
                                    console.log('Load complete !!!');
                                });
                                this.integralExchangeRequest(300)

                                // 亚马逊用户兑换成功后....
                                localStorage.setItem("jumpStart",3)
                                this.requestAxiosJump()
                                this.setState({
                                    ltStartJump:0,
                                    jumpIntegral:0
                                })

                                
                             } },
                            ])}
                         >3000积分兑换</Button>

                    </div>
                    {/* 500日元优惠券 */}
                    <div className="main-integral-500"  onClick={this.twoOnHanldClick}>
                        <div className="main-integral-top"
                        onClick={this.onIntegralClickDetail.bind(this,"2")}
                        >
                            <h4>500</h4> <h5>クーポン</h5>
                        </div>
                        <Button 
                        className="main-integral-bottom"
                        style={{fontSize:14,}}
                        onClick={() => operation([
                            { text:'5000分兑500日元',style:{textAlign:'center',color:"rgb(235, 37, 4)",fontWeight:900}},
                            { text: 'すでに代金引換',style:{background:"skyblue",color:"#fff",textAlign:"center"}, onPress: () => {
                                if(userCountIntegral < 5000){
                                    Toast.offline('残高が足りない、レビューを書いてポイントが貯まる !!!', 1);
                                    return;
                                }
                                Toast.loading('Loading...', 1, () => {
                                    console.log('Load complete !!!');
                                });
                                console.log("发请求.....500")
                                this.integralExchangeRequest(500)
                             }},
                            ])}
                         >5000积分兑换</Button>
                    </div>
                    {/* 1000日元优惠券 */}
                    <div className="main-integral-1000"  onClick={this.threeOnHanldClick}>
                        <div className="main-integral-top"
                        onClick={this.onIntegralClickDetail.bind(this,"3")}
                        >
                            <h4>1000</h4> <h5>クーポン</h5>
                        </div>
                        <Button 
                        className="main-integral-bottom"
                        style={{fontSize:14,}}
                        onClick={() => operation([
                            { text:'10000分兑1000日元',style:{textAlign:'center',color:"rgb(235, 37, 4)",fontWeight:900}},
                            { text: 'すでに代金引換',style:{background:"skyblue",color:"#fff",textAlign:"center"}, onPress: () => {
                                if(userCountIntegral < 10000){
                                    Toast.offline('残高が足りない、レビューを書いてポイントが貯まる !!!', 1);
                                    return;
                                }
                                console.log("发请求.....1000")
                                Toast.loading('Loading...', 1, () => {
                                    console.log('Load complete !!!');
                                });
                                this.integralExchangeRequest(1000)
                            }},
                            ])}
                         >10000积分兑换</Button>
                    </div>
                </div>
               
            </div>:<GoodsIntegral onClicked={this.onChangeState.bind(this)}></GoodsIntegral>
            }
            {/* 兑换提示..... */}
            {/* {this.state.localStorageExChangeJumpStart === 1?
            <div className="integralStart">
                <img style={{width:40,height:40}} src={Jump}></img>
                <div className="navigator-good-clear-integral"> 
                    <h4 className="naviagtor-good-clear-order-integral" onClick={this.clearNaviagtorOrderTop}></h4>
                        <p className="naviagtor-guide-page-good-message-integral">点击兑换:点击进入赚积分页面,用户在店铺购买商品后进行留评并获得积分
                        </p>
                    </div>
                </div>:""    
            } */}
            {/* 优惠券详情..... */}
                {this.state.integralDetail? 
                    <div className="integralDetail">
                        <h2 className="integralTitle">{integralDetailIns.integralTitle}</h2>
                        <p><span className="integralIntegralspan1">代金引換:</span>{integralDetailIns.integralCountSum}<span className="integralIntegralspan2"></span> </p>
                           
                        <h3 onClick={this.clearGoodsDetail}>
                            ×
                        </h3>
                    </div>
                :""}
          </div>
        )
    }
}
export default withRouter(Index)
